package com.advertisementsystem.Servie.Impl;

import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Mapper.BillMapper;
import com.advertisementsystem.Servie.IncomeService;
import com.advertisementsystem.entity.Bill;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Year;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IncomeServiceImpl implements IncomeService {

    @Autowired
    private BillMapper billMapper;

    @Override
    public Map<String, Object> getMonthlyIncome() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取当前登录的设备拥有者ID
            // 获取当前用户
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();

            Long deviceOwnerId = loginUser.getUser().getId();
            // 获取当前年月和上一个月
            YearMonth currentMonth = YearMonth.now();
            YearMonth lastMonth = currentMonth.minusMonths(1);

            // 查询当月收入
            BigDecimal currentMonthIncome = billMapper.getMonthlyIncome(
                    deviceOwnerId,
                    currentMonth.getYear(),
                    currentMonth.getMonthValue());

            // 查询上月收入
            BigDecimal lastMonthIncome = billMapper.getMonthlyIncome(
                    deviceOwnerId,
                    lastMonth.getYear(),
                    lastMonth.getMonthValue());

            // 计算环比增长率
            double growth = 0;
            if (lastMonthIncome != null && lastMonthIncome.compareTo(BigDecimal.ZERO) > 0) {
                growth = currentMonthIncome.subtract(lastMonthIncome)
                        .divide(lastMonthIncome, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .doubleValue();
            }

            // 保留两位小数
            growth = new BigDecimal(growth).setScale(2, RoundingMode.HALF_UP).doubleValue();

            result.put("totalIncome", currentMonthIncome);
            result.put("growth", growth);

            log.info("设备拥有者[{}]查询月度收入：{}，环比增长：{}%",
                    deviceOwnerId, currentMonthIncome, growth);
        } catch (Exception e) {
            log.error("获取月度收入数据异常", e);
            result.put("totalIncome", BigDecimal.ZERO);
            result.put("growth", 0);
        }

        return result;
    }

    @Override
    public Map<String, Object> getYearlyIncomeStats(Integer year) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> monthlyData = new ArrayList<>();

        try {
            // 获取当前登录的设备拥有者ID
            // 获取当前用户
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();

            Long deviceOwnerId = loginUser.getUser().getId();
            // 如果未指定年份，则使用当前年
            if (year == null) {
                year = Year.now().getValue();
            }

            // 查询年度月度收入数据
            List<Map<String, Object>> monthlyStats = billMapper.getMonthlyIncomeStats(deviceOwnerId, year);

            // 计算年度总收入
            BigDecimal yearlyTotal = BigDecimal.ZERO;

            // 构建月度数据，确保12个月都有数据
            Map<Integer, BigDecimal> monthMap = new HashMap<>();
            for (Map<String, Object> stat : monthlyStats) {
                Integer month = (Integer) stat.get("month");
                BigDecimal total = (BigDecimal) stat.get("total");
                monthMap.put(month, total);
                yearlyTotal = yearlyTotal.add(total);
            }

            // 生成完整的月度数据（1-12月）
            for (int i = 1; i <= 12; i++) {
                Map<String, Object> monthData = new HashMap<>();
                monthData.put("month", i);
                monthData.put("total", monthMap.getOrDefault(i, BigDecimal.ZERO));
                monthlyData.add(monthData);
            }

            result.put("year", year);
            result.put("yearlyTotal", yearlyTotal);
            result.put("monthlyData", monthlyData);

            log.info("设备拥有者[{}]查询{}年度收入统计，总收入：{}",
                    deviceOwnerId, year, yearlyTotal);
        } catch (Exception e) {
            log.error("获取年度收入统计异常", e);
            result.put("year", year);
            result.put("yearlyTotal", BigDecimal.ZERO);
            result.put("monthlyData", monthlyData);
        }

        return result;
    }

    @Override
    public Page<Map<String, Object>> getIncomeDetails(String status, Integer pageNum, Integer pageSize) {
        Page<Map<String, Object>> resultPage = new Page<>(pageNum, pageSize);

        try {
            // 获取当前登录的设备拥有者ID
            // 获取当前用户
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();
            Long deviceOwnerId = loginUser.getUser().getId();

            // 构建查询条件
            LambdaQueryWrapper<Bill> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Bill::getDeviceOwnerId, deviceOwnerId);

            // 根据状态筛选
            if (StringUtils.hasText(status) && !"ALL".equalsIgnoreCase(status)) {
                queryWrapper.eq(Bill::getStatus, status.toUpperCase());
            }

            // 排序：已支付的按支付时间降序，其他按创建时间降序
            queryWrapper.orderByDesc(status != null && "PAID".equalsIgnoreCase(status)
                    ? Bill::getPaymentDate : Bill::getCreatedTime);

            // 执行分页查询
            Page<Bill> page = new Page<>(pageNum, pageSize);
            Page<Bill> billPage = (Page<Bill>) billMapper.selectPage(page, queryWrapper);

            // 转换为Map结果
            List<Map<String, Object>> records = billPage.getRecords().stream().map(bill -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", bill.getId());
                map.put("negotiationId", bill.getNegotiationId());
                map.put("advertiserId", bill.getAdvertiserId());
                map.put("amount", bill.getAmount());
                map.put("status", bill.getStatus());
                map.put("dueDate", bill.getDueDate());
                map.put("paymentDate", bill.getPaymentDate());
                map.put("createdTime", bill.getCreatedTime());
                return map;
            }).collect(Collectors.toList());

            // 设置结果页面
            resultPage.setRecords(records);
            resultPage.setTotal(billPage.getTotal());
            resultPage.setCurrent(billPage.getCurrent());
            resultPage.setSize(billPage.getSize());

            log.info("设备拥有者[{}]查询账单明细，状态：{}，页码：{}，每页大小：{}，总记录数：{}",
                    deviceOwnerId, status, pageNum, pageSize, resultPage.getTotal());
        } catch (Exception e) {
            log.error("获取账单明细异常", e);
        }

        return resultPage;
    }

    @Override
    public Map<String, Object> getIncomeSummary() {
        try {
            // 获取当前登录的设备拥有者ID
            // 获取当前用户
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();
            Long deviceOwnerId = loginUser.getUser().getId();

            // 查询收入汇总信息
            Map<String, Object> summary = billMapper.getIncomeSummary(deviceOwnerId);

            log.info("设备拥有者[{}]查询收入汇总信息", deviceOwnerId);

            return summary;
        } catch (Exception e) {
            log.error("获取收入汇总信息异常", e);
            Map<String, Object> emptySummary = new HashMap<>();
            emptySummary.put("totalPaid", BigDecimal.ZERO);
            emptySummary.put("totalUnpaid", BigDecimal.ZERO);
            emptySummary.put("totalOverdue", BigDecimal.ZERO);
            emptySummary.put("paidCount", 0);
            emptySummary.put("unpaidCount", 0);
            emptySummary.put("overdueCount", 0);
            return emptySummary;
        }
    }

    @Override
    public List<Map<String, Object>> getRecentIncomeRecords(Integer limit) {
        try {
            // 获取当前登录的设备拥有者ID
            // 获取当前用户
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();
            Long deviceOwnerId = loginUser.getUser().getId();

            // 获取最近收入记录
            List<Map<String, Object>> records = billMapper.getRecentIncomeRecords(deviceOwnerId, limit);

            log.info("设备拥有者[{}]查询最近{}条收入记录", deviceOwnerId, limit);

            return records;
        } catch (Exception e) {
            log.error("获取最近收入记录异常", e);
            return new ArrayList<>();
        }
    }
}